﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Configuration;

using DasIdeen.ViewEntity;
using Ivy.Common.Framework.GeneralUtility;
using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.IBusinessLogic;
using Ivy.UserRegistration.BusinessLogic;
using Ivy.SiteAdmin.Entity;
using Ivy.SiteAdmin.IBusinessLogic;
using Ivy.SiteAdmin.BusinessLogic;



namespace DasIdeen
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            Exception ex = HttpContext.Current.Server.GetLastError();
            //if (ex.GetType().ToString() != "System.Web.HttpException")
            //{
                const string constExceptionLoggerOn = "ExceptionLoggerOn";
                const string constExceptionLogFileName = "ExceptionLogFileName";
                string _ServerRootPath = Server.MapPath("~/");
                AppSettingsReader _AppSettingsReader = new AppSettingsReader();
                string lIsExceptionLoggerOn = _AppSettingsReader.GetValue(constExceptionLoggerOn, typeof(string)).ToString();
                string lFullPathLogFileName = _AppSettingsReader.GetValue(constExceptionLogFileName, typeof(string)).ToString();
                if (lIsExceptionLoggerOn == "True")
                {
                    if (lFullPathLogFileName != "DataBase")
                    {
                        lFullPathLogFileName = _ServerRootPath + _AppSettingsReader.GetValue(constExceptionLogFileName, typeof(string)).ToString();
                        string lLogText = string.Empty;
                        lLogText = "=========================================\r\n" + DateTime.Now + " , \r\n[APPLICATION]:\t" + ex.GetType().ToString() + " - " + ex.Source + " , \r\n[METHOD]:\t" + ex.TargetSite.ToString() + " , \r\n[MESSAGE]:\t" + ex.Message + " , \r\n[STACKTRACE]:\t" + ex.StackTrace + "\r\n=========================================\r\n";
                        FileUtility lFileUtility = new FileUtility();
                        lFileUtility.WriteToLogFile(lLogText, lFullPathLogFileName);
                    }
                    else
                    {
                        Sys_ErrorLog lSys_ErrorLog = new Sys_ErrorLog();
                        SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                        lSys_ErrorLog.ApplicationName = ex.GetType().ToString() + " - " + ex.Source;
                        lSys_ErrorLog.MethodName = ex.TargetSite.ToString();
                        lSys_ErrorLog.ErrorMessage = ex.Message;
                        lSys_ErrorLog.StackTrace = ex.StackTrace;
                        lSys_ErrorLog.Sys_CreatedByID = "-1";
                        lSiteAdminContentManagementBus.SaveSys_ErrorLogDetails(lSys_ErrorLog);
                    }
                }
            //}
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            UserContext tempUserSession = new UserContext();
            tempUserSession.UserSessionID = HttpContext.Current.Session.SessionID;
            tempUserSession.CultureInfo = GetUserCultureInfo();
            tempUserSession.UserIPAddress = GetUserIPAddress();
            tempUserSession.UserBrowser = HttpContext.Current.Request.Browser.Browser;
            tempUserSession.UserSessionStartTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            //tempUserSession.CurrentUser = lUser;
            Session["UserContext"] = tempUserSession;
            WriteSessionLog(tempUserSession);
        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

        #region Private Methods
        private string GetUserIPAddress()
        {
            //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
            //client connecting to a web server through an HTTP proxy or load balancer
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
            }
            return ip;
        }
        private string GetUserCultureInfo()
        {
            //Currently we are treating all user with same cultural info. We will change ir based of user session.
            AppSettingsReader _AppSettingsReader = new AppSettingsReader();
            string _CultureInfo = _AppSettingsReader.GetValue("CultureInfo", typeof(string)).ToString();
            return _CultureInfo;
        }

        private void WriteSessionLog(UserContext pUserSession)
        {
            const string constSessionLoggerOn = "SessionLoggerOn";
            const string constSessionLogFileName = "SessionLogFileName";
            string _ServerRootPath = Server.MapPath("~/");
            AppSettingsReader _AppSettingsReader = new AppSettingsReader();
            string lIsExceptionLoggerOn = _AppSettingsReader.GetValue(constSessionLoggerOn, typeof(string)).ToString();
            string lFullPathLogFileName = _AppSettingsReader.GetValue(constSessionLogFileName, typeof(string)).ToString();
            if (lIsExceptionLoggerOn == "True")
            {
                if (lFullPathLogFileName != "DataBase")
                {
                    lFullPathLogFileName = _ServerRootPath + _AppSettingsReader.GetValue(constSessionLogFileName, typeof(string)).ToString();
                    string lLogText = string.Empty;
                    lLogText = "UserSessionID - " + pUserSession.UserSessionID + " , UserIPAddress - " + pUserSession.UserIPAddress + " , UserSessionStartTime - " + pUserSession.UserSessionStartTime + " , UserBrowser - " + pUserSession.UserBrowser;
                    FileUtility lFileUtility = new FileUtility();
                    lFileUtility.WriteToLogFile(lLogText, lFullPathLogFileName);
                }
                else
                {
                    Sys_SessionLog lSys_SessionLog = new Sys_SessionLog();
                    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    lSys_SessionLog.UserSessionID = pUserSession.UserSessionID;
                    lSys_SessionLog.UserIPAddress = pUserSession.UserIPAddress;
                    lSys_SessionLog.UserBrowserName = pUserSession.UserBrowser;
                    lSys_SessionLog.Sys_CreatedByID = "-1";

                    lSys_SessionLog.UserSessionStartTime = DateTime.Parse(pUserSession.UserSessionStartTime);

                    if (lUserRegistrationBus.SaveUserSys_SessionLogDetails(lSys_SessionLog))
                    {

                    }
                }
            }
        }
        #endregion Private Methods

    }
}
